<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket群聊通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;
    function openSocket() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl="http://82.157.192.250/im-server-ws/chat2/"+ $("#roomId").val();
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl,[$("#token").val()]);
            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                setMsg("登录成功！！！");
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                setMsg(msg.data);
            };
            //关闭事件
            socket.onclose = function() {
                setMsg("BYE BYE！！！");
            };
            //发生了错误事件
            socket.onerror = function() {
                setMsg("连接服务器错误！！！");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            //获取文本框的值
            var msg = document.getElementById("contentText").value;
            setMsg('自己:' + msg);
            socket.send(msg);
        }
    }
    //在div中写信息的方法
    function setMsg(msg) {
        document.getElementById("message").innerHTML+=msg+"<br/>";
    }
    //用户点击按钮退出聊天室
    function exitTalk() {
        socket.close();
    }
    //用户点击按钮清空聊天记录
    function clearTalk() {
        $("#message").html("");
    }
</script>
<body>
<p>【token】：<div><input id="token" name="token" type="text" value="64"></div>
<p>【roomId】：<div><input id="roomId" name="roomId" type="text" value="10"></div>
<p>【contentText】：<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】：<div><button onclick="openSocket()">开启socket</button></div>
<p>【操作】：<div><button onclick="exitTalk()">关闭socket</button></div>
<p>【操作】：<div><button onclick="sendMessage()">发送消息</button></div>
<p>【操作】：<div><button onclick="clearTalk()">清空消息记录</button></div>
<br>
<div id="message"></div>
</body>

</html>